<template>
  <div class="body">
    <div style="height: 1px;color: #999999;margin: 12px 0;"></div>
    <div class="day-statistics">
      <div style="display: flex;">
        <div class="day-form">
          <div class="form-item">
            <div class="day-form-tit">考勤组：</div>
            <a-select default-value="请选择考勤组" v-model="searchData.groupId" class="day-form-in">
              <a-select-option v-for="(item, index) in groupArr" :key="index" :value="item.id">
                {{ item.groupName || '' }}
              </a-select-option>
            </a-select>
          </div>
          <div class="form-item">
            <div class="day-form-tit">部门：</div>
            <a-cascader
                :field-names="{ label: 'name', value: 'id', children: 'child' }"
                :options="deptArr"
                expand-trigger="hover"
                @change="depChange"
                placeholder="请选择"
                class="day-form-in"/>
          </div>
          <div class="form-item">
            <div class="day-form-tit">教师姓名：</div>
            <a-input v-model="searchData.userName" placeholder="请输入教师姓名" class="day-form-in" />
          </div>
          <a-button class="day-form-btn" type="primary" @click="getList()" style="margin-left: 40px;">搜索</a-button>
          <a-button class="day-form-btn" @click="reset">重置</a-button>
      </div>
      <div>
        <div style="float: right;margin-left: 30px;">
          <a-button type="link" :class="[ type == 'today' ? '' : 'tx-blacok' ]" tx-blacok @click="setSearchCondition('today')">
            今日
          </a-button>
          <a-button type="link" :class="[ type == 'weeks' ? '' : 'tx-blacok' ]" @click="setSearchCondition('weeks')">
            本周
          </a-button>
          <a-button type="link" :class="[ type == 'months' ? '' : 'tx-blacok' ]" @click="setSearchCondition('months')">
            本月
          </a-button>
          <a-range-picker @change="timeChange">
            <a-button type="link" style="color: black">
              <a-icon type="question-circle" /> 自定义时间 <a-icon type="down" />
            </a-button>
          </a-range-picker>
          <a-button>导出</a-button>
        </div>
      </div>
      </div>
      <a-radio-group v-model="mode" style="margin: 14px 0">
        <a-radio-button value="0">
          显示时间
        </a-radio-button>
        <a-radio-button value="1">
          显示次数
        </a-radio-button>
      </a-radio-group>
      <div v-if="mode == 0">
        <a-table :pagination="false" :columns="columns" :data-source="workList" class="table" bordered :scroll="{ x: tableWidth }"></a-table>
        <div class="" style="display: flex;justify-content: flex-end;margin-top: 20px;" v-if="workList.length">
          <a-pagination @change="onChange" :default-current="searchData.page"  :pageSize="pageSize" :total="total" />
        </div>
      </div>
      <div v-if="mode == 1">
        <a-table :pagination="false"  :columns="columns" :data-source="workList" class="table" bordered></a-table>
        <div class="" style="display: flex;justify-content: flex-end;margin-top: 20px;" v-if="workList.length">
          <a-pagination @change="onChange" :default-current="searchData.page"  :pageSize="pageSize" :total="total" />
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped="scoped" lang="scss">
  .body {
    padding: 24px 0;
  }

  .tx-blacok {
    color: black;
  }

  ::v-deep .ant-tabs-nav-container {
    margin-left: 24px;
  }

  .day-statistics {
    margin: 0 24px;

    .day-form {
      display: flex;
      flex-wrap: wrap;
      .day-form-tit {
        white-space: nowrap;
      }
      .form-item {
        display: flex;
        align-items: center;
        // margin: 0 0 24px 0;
        width: 220px;
        margin-right: 10px;
      }
      .day-form-in {
        width: 220px;
      }
      .day-form-btn {
        margin-right: 10px;
      }
    }

    .table {
      margin-top: 24px;
    }
  }
</style>
<script>
  import {
    dailyPage,
    getPunchTitle,
    timePage
  } from '@/api/clock'
  import moment from 'moment';
 import {
   tree,
 } from '@/api/tree'
 import { list } from '@/api/clock'

  export default {
    data() {
      return {
        total: 100,
        pageSize: 10,

        type: '',

        pagination: {
                total: 0,
                pageSize: 100,//每页中显示10条数据
                showSizeChanger: true,
                pageSizeOptions: ["10", "20", "50", "100"],//每页中显示的数据
                showTotal: total => `共有 ${total} 条数据`,  //分页中显示总的数据
              },

        // 考勤组
        groupArr: [],
        // 部门
        deptArr: [],

        columns: [],

        searchData: {
          groupId: '',
          deptId: [],
          userName: '',
          page: 1,
          limit: 10,
          queryStartDate: moment().startOf('weeks').format('YYYY-MM-DD'), // 默认周
          queryEndDate: moment().endOf('weeks').format('YYYY-MM-DD')      // 默认月
        },
        list: [],
        workList: [],
        mode: 0,
        dynamicTableTit: null,
        tableWidth: '100%'
      }
    },
    mounted() {
      list()
      .then(response => {
        response.data.unshift({
          groupName: '请选择',
          id: ''
        })
        this.groupArr = response.data
      })
      tree({ parentId: 0}).then(response => {
        this.deptArr = response.data.list
      })
      this.setSearchCondition("today")
      this.getList()
    },
    watch: {
      mode () {
        this.getList()
      }
    },
    methods: {

      reset (e) {
        console.log("e: ",e);
      },

      depChange (e, k) {
        this.searchData.deptId = e[e.length - 1]
      },

      timeChange (e, k) {
        this.searchData.queryStartDate = k[0]
        this.searchData.queryEndDate = k[1]
        this.getList()
      },

      onChange (e) {
        this.searchData.page = e
        this.getList()
      },

      // 设置表头
      enumerateDaysBetweenDates (startDate, endDate) {
        let daysList = []
        const start = moment(startDate)
        const end = moment(endDate)
        const day = end.diff(start, "days")
        daysList.push(start.format("YYYY-MM-DDdddd"))
        for (let i = 1; i <= day; i++) {
          daysList.push(start.add(1, "days").format("YYYY-MM-DDdddd"))
        }
        return daysList
      },

      // 设置搜索条件和表头
      setSearchCondition (type = 'today') {
        this.type = type
        if(type == 'today') {
          this.tableWidth = '100%'
          this.searchData.queryStartDate = moment().startOf('days').format('YYYY-MM-DD')
          this.searchData.queryEndDate = moment().endOf('days').format('YYYY-MM-DD')
        }
        if(type == 'weeks') {
          this.tableWidth = '100%'
          this.searchData.queryStartDate = moment().startOf('weeks').format('YYYY-MM-DD')
          this.searchData.queryEndDate = moment().endOf('weeks').format('YYYY-MM-DD')
        }
        if(type == 'months') {
          this.tableWidth = '400%'
          this.searchData.queryStartDate = moment().startOf('months').format('YYYY-MM-DD')
          this.searchData.queryEndDate = moment().endOf('months').format('YYYY-MM-DD')
        }
        this.dynamicTableTit = this.enumerateDaysBetweenDates(this.searchData.queryStartDate, this.searchData.queryEndDate)
        // 兼容后端星期字串
        let dynamicTableTit = []
        this.dynamicTableTit.forEach(item => {
          if (item.includes('星期一')) {
            dynamicTableTit.push(item.replace(/星期一/, "(周一)"))
          }
          if (item.includes('星期二')) {
            dynamicTableTit.push(item.replace(/星期二/, "(周二)"))
          }
          if (item.includes('星期三')) {
            dynamicTableTit.push(item.replace(/星期三/, "(周三)"))
          }
          if (item.includes('星期四')) {
            dynamicTableTit.push(item.replace(/星期四/, "(周四)"))
          }
          if (item.includes('星期五')) {
            dynamicTableTit.push(item.replace(/星期五/, "(周五)"))
          }
          if (item.includes('星期六')) {
            dynamicTableTit.push(item.replace(/星期六/, "(周六)"))
          }
          if (item.includes('星期日')) {
            dynamicTableTit.push(item.replace(/星期日/, "(周日)"))
          }
        })
        this.dynamicTableTit = dynamicTableTit
        let columns = [
          {
            title: '教师姓名',
            dataIndex: 'userName',
            width: 120,
            customRender: (value, row, index) => {
              const obj = {
                children: value,
                attrs: {},
              };
              obj.attrs.rowSpan = row.deptNameRows
              return obj
            }
          },
          {
            title: '考勤组',
            dataIndex: 'groupName',
            width: 80,
          },
          {
            title: '部门',
            dataIndex: 'deptName',
            width: 80,
          },
          {
            title: '类型',
            dataIndex: 'typeList',
            width: 80,
          }
        ]
        this.dynamicTableTit.forEach(item => {
          columns.push({
            title: item,
            dataIndex: item,
            key: item,
            width: 100,
          })
        })
        this.columns = columns
        this.getList()
      },
      getList() {
        let fn = this.mode == 0 ? dailyPage : timePage
        fn(this.searchData)
        .then(response => {
          let records = response.data.records
          this.total = response.data.total
          records.forEach(row => {
            this.dynamicTableTit.forEach(day => {
              // 接口数据中没有找到当天
              if (!row.punchList[day]) {
                row[day] = new Array(row.typeList.length).fill('')
              } else {
                row[day] = row.punchList[day]
              }
            })
          })
          // 数组展开组装
          let tempArr = []
          let k
          // debugger
          records.forEach((row, rowIndex) => {
            row.typeList.forEach((item, index) => {
              let obj = {}
              obj.userName = row.userName
              obj.deptName = row.deptName

              obj.groupName = row.groupName

              obj.typeList = row.typeList[index]
              this.dynamicTableTit.forEach(day => {
                obj[day] = (row[day])[index]
              })
              // debugger
              let cc = obj.userName  + '_' + rowIndex
              if (cc== k) {

                obj.deptNameRows = 0
              } else {
                obj.deptNameRows = row.typeList.length
              }
              k = row.userName + '_' + rowIndex
              tempArr.push(obj)
            })
          })
          this.workList = tempArr
        })
      },
    }
  }
</script>
